/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Nov 27, 2013  4:36:06 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : history.logs
 * File Name : QueueServerThreadPool.java
 * TODO
 */
package history.logs;

import java.sql.Connection;
import java.util.Date;

import org.apache.log4j.Logger;

import promis.db.connection.dbHelper;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Nov 27, 2013 : 4:36:06 PM 
 * CreateBy=Chatree Siangklom
 * 
 * QueueServerThreadPool
 * TODO
 */
public class QueueServerThreadPool {
	
	
	private static final Logger logging = Logger.getLogger(QueueServerThreadPool.class);
	private static final long MEGABYTE = 1024L * 1024L;

	/**
	 * 
	 * Date =Nov 27, 2013 : 4:37:34 PM 
	 * CreateBy=Chatree Siangklom
	 * long
	 * TODO
	 * @param bytes
	 * @return
	 */
	private static long bytesToMegabytes(long bytes) {		  		  
		  return (bytes / MEGABYTE);
	}
	
	/**
	 * Date =Nov 27, 2013 : 3:57:40 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	private static void logsHits(Connection conn) throws Exception {
		try{

			conn.setAutoCommit(true);
			String sql = " SELECT LOGSHITS_EXEC FROM DUAL ";
			java.sql.Statement stmt = conn.createStatement();
			stmt.executeQuery(sql);
			
			stmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if((conn != null) && (!conn.isClosed()))
				conn.setAutoCommit(false);
		}
		return;
	}
	
	public static void logsHitsThreads()throws Exception {
		try{
			dbHelper dbHelp = new dbHelper();
			Connection conn = dbHelp.getConn();
			try {
				 while(true)
				 {
					 if(conn == null)
						 conn = dbHelp.getConn();
					 
					 if(conn.isClosed())
						 conn = dbHelp.getConn();		
					 
					 if(conn == null)
						 System.err.println("Connection is null !!!, Date:" + new Date().toString());
					 else
						 logsHits(conn);
					 
					// Get the Java runtime
					Runtime runtime = Runtime.getRuntime();
				    // Calculate the used memory		    
					long memory = runtime.totalMemory() - runtime.freeMemory();
					System.out.println("totalMemory: " + bytesToMegabytes(runtime.totalMemory()) + "MB."  + " //freeMemory: " + bytesToMegabytes(runtime.freeMemory()) + "MB."  + " //Used memory is bytes: " +  memory + " //Used memory is megabytes: " + bytesToMegabytes(memory)  + "MB.");
					    
				    // Run the garbage collector
				    runtime.gc();
				    //System.gc();
				    Thread.sleep(5000);
				    //queue = null;
				 }
			} catch (Exception e) {
				e.printStackTrace();
				logging.error(e.getMessage());
				System.out.println(e.getMessage());
			}
		}catch(Exception e){
			e.printStackTrace();
			logging.error(e.getMessage());
			System.out.println(e.getMessage());
			logsHitsThreads();
		}
	}

}
